import { messages } from 'share/common';
import React, { Component } from 'react';
import errorMessage from 'share/errorMessage';
import ScanSendService from './scan-send.service';
import nothing from 'images/send-code/nothing.png';
import 'styles/financial-management/scan-send.scss';
import { Input, Button, message, Form, Icon, Popover, Radio } from 'antd';
import { connect } from 'react-redux';
import moment from 'moment'

@Form.create()
@connect(mapStateToProps)
class ScanSendDelivery extends Component {
  state = {
    showInput: false,
    entities: [],
    deliveryCode: '',
    submitLoading: false,
    visible: false,
    words: {
      'delivery-receive': {
        secondStep: messages('expense-13.key12')/*请添加收到单据*/,
        submit: messages('expense-13.key13')/*收单*/,
        operation: 1001,
        scanExpense: 'DELIVERY_BILL_RECEIVE'
      },
      'delivery-send': {
        secondStep: messages('expense-13.key14')/*请添加寄出单据*/,/*请添加寄出单据*/
        submit: messages('expense-13.key15')/*寄单*/,/*寄单*/
        operation: 1000,
        scanExpense: 'DELIVERY_BILL_SEND'
      }
    },
    mode: window.localStorage.getItem('delivery-receive-mode') || 'receive', // 获取收单配置 默认'收单'
    radioChild: [
      {
        name: messages('expense-13.key13')/*收单*/,
        extra: messages('expense-13.key16')/*仅收单，不进行审核操作*/,
        value: 'receive'
      },
      {
        name: messages('expense-13.key17')/*收单并实时审核*/,
        extra: messages('expense-13.key18')/*审核通过操作实时处理，处理结果即时返回*/,
        value: 'receiveAndReview'
      },
      {
        name: messages('expense-13.key19')/*收单并后台审核*/,
        extra: messages('expense-13.key20')/*审核通过操作后台处理，不等待处理结果，可至待审核列表查看审核通过失败单据*/,
        value: 'receiveAndReviewBack'
      }],
    receiveWithAudit: {
      receive: null,
      receiveAndReview: 1000,
      receiveAndReviewBack: 1001,
    }
  };

  handleOnPressEnter = (e) => {
    const { entities, words } = this.state;
    const { symbol } = this.props;
    ScanSendService.scanExpense(e.target.value, words[symbol].scanExpense)
      .then(res => {
        if (res.data.code === '0000') {
          res.data.receiveScanCodeDate = moment().utc().format();
          entities.unshift(res.data);
          message.success(res.data.msg);
          this.setState({ entities });
        } else {
          message.error(res.data.msg);
        }
        this.props.form.resetFields();
        this.input.focus();
      })
      .catch(err => {
        this.props.form.resetFields();
        this.input.focus();
        errorMessage(err.response);
      });
  };

  handleDeliveryCode = (e) => {
    this.setState({ deliveryCode: e.target.value });
  };


  handleSubmit = async () => {
    const { entities, deliveryCode, receiveWithAudit, mode, words } = this.state;
    let { sendData, onChange, symbol } = this.props;
    if (!deliveryCode) {
      message.error(messages('expense-13.key21')/*请输入/扫码输入快递单号*/);
      return;
    }
    if (!entities[0]) {
      message.error(messages('expense-13.key22')/*请输入/扫码输入单据*/);
      return;
    }
    const params = {
      deliveryCode,
      operation: words[symbol].operation,
      entities: entities.map(item => {
        const { entityCode, entityType, receiveScanCodeDate } = item;
        return { entityOID: entityCode, entityType, receiveScanCodeDate };
      })
    };
    this.setState({ submitLoading: true });
    symbol === 'delivery-receive' && (params.receiveWithAudit = receiveWithAudit[mode]);
    try {
      const ret = await ScanSendService.sendDelivery(params);
      if (ret.data.success) {
        sendData = ret.data.businessCodeList.concat(sendData);
        onChange(sendData);
        message.success(ret.data.msg);
        this.deLiveryInput.focus();
        this.setState({
          entities: [],
          deliveryCode: '',
          showInput: false
        });
      } else {
        message.error(ret.data.msg);
      }
    }
    catch (e) {

    }
    this.setState({ submitLoading: false });

  };

  componentDidMount() {
    setTimeout(() => {
      this.deLiveryInput.focus();
    }, 200);
  }

  handleVisibleChange = visible => {
    this.setState({ visible });
  };

  handleDeliverySetting = () => {
    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((err, value) => {
      window.localStorage.setItem('delivery-receive-mode', value.mode);
      this.setState({ ...value, visible: false });
    });
  };

  renderPopoverTitle = () => (
    <div className="scan-send-option-delivery-setting-title">
      {messages('expense-13.key23')/*操作设置*/}
      <Icon type="close" onClick={() => {
        this.setState({ visible: false });
      }}/>
    </div>
  );

  renderPopoverContent = () => {
    const { form: { getFieldDecorator } } = this.props;
    const { mode, radioChild } = this.state;
    return (
      <section className="scan-send-option-delivery-setting-content">
        <Form>
          <Form.Item>
            {getFieldDecorator('mode', {
              initialValue: mode,
            })(
              <Radio.Group>
                {
                  radioChild.map(item => (
                      <Radio value={item.value} className="scan-send-option-delivery-setting__radio">
                        <section>
                          <div>{item.name}</div>
                          <div className="scan-send-option-delivery-setting-body">{item.extra}</div>
                        </section>
                      </Radio>
                    )
                  )
                }
              </Radio.Group>
            )}
          </Form.Item>
          <section className="scan-send-option-delivery-setting-footer">
            <Button type="primary" onClick={this.handleDeliverySetting}>
              {messages('common.ok')/*确定*/}
            </Button>
          </section>
        </Form>
      </section>
    );
  };

  renderSettingButton = () => {
    const { visible } = this.state;
    return (
      <Popover
        visible={visible}
        style={{ width: 356 }}
        content={this.renderPopoverContent()}
        placement="topRight"
        trigger="click"
        title={this.renderPopoverTitle()}
        onVisibleChange={this.handleVisibleChange}
      >
        <Button type="primary" className="scan-send-option-delivery-setting">
          <Icon type="setting"/>
        </Button>
      </Popover>);
  };

  render() {
    const { showInput, entities, deliveryCode, submitLoading, words, mode, radioChild } = this.state;
    const { symbol, options } = this.props;
    return (
      <section className="scan-send-option-delivery">
        <section className="scan-send-option-delivery-step">
          <div className="scan-send-option-delivery-number">1</div>
          <div className="scan-send-option-delivery-line"/>
          <div className="scan-send-option-delivery-number">2</div>
        </section>
        <section className="scan-send-option-delivery-content">
          <section className="scan-send-option-delivery-title">
            {messages('expense-13.key24')/*填写快递单号*/}
          </section>
          <section className="scan-send-option-delivery-input">
            <div className="scan-send-option-delivery-label">
              {messages('expense-13.key25')/*快递单号*/}
            </div>
            <Input
              className="scan-send__input"
              onChange={this.handleDeliveryCode}
              value={deliveryCode}
              ref={input => this.deLiveryInput = input}
              placeholder={messages('expense-13.key26')/*请使用扫码枪/手动录入*/}
            />
          </section>

          <section className="scan-send-option-delivery-title">
            <div>{words[symbol].secondStep}</div>
            {
              showInput
                ? this.props.form.getFieldDecorator('code')(
                <Input
                  onBlur={() => this.setState({ showInput: false })}
                  ref={input => this.input = input}
                  className="scan-send-option-delivery-scan-input"
                  onPressEnter={this.handleOnPressEnter}
                />)
                : <div className="scan-send-option-delivery-scan" onClick={() => this.setState({ showInput: true }, () => setTimeout(() => {this.input.focus();}))}>{messages('expense-13.key27')/*+扫码或输入单据*/}</div>
            }
          </section>
          <section className="scan-send-option-delivery-expense">
            {
              entities[0]
                ? entities.map(item => <span
                  className="scan-send-option-delivery-business">{item.businessCode}</span>)
                : <div className="scan-send-option-delivery-desc"><span><img className="scan-send-option-delivery__img" src={nothing}/>{messages('expense-13.key26')/*请使用扫码枪/手动录入*/}</span>
                </div>
            }
          </section>
          <section className="scan-send-option-delivery-send">
            <Button.Group style={{ width: '80%', textAlign: 'center' }}>
              <Button
                type="primary"
                className={`scan-send-option-delivery-submit ${symbol === 'delivery-receive' && (options.auditBaseConfig || {}).receiveWithAudit && 'scan-send-option-delivery_width'}`}
                loading={submitLoading}
                onClick={this.handleSubmit}
              >
                {symbol === 'delivery-receive' ? radioChild.filter(item => item.value === mode)[0].name : words[symbol].submit}
              </Button>
              {
                symbol === 'delivery-receive' && (options.auditBaseConfig || {}).receiveWithAudit && this.renderSettingButton()
              }
            </Button.Group>
          </section>
        </section>
      </section>
    );
  }
}

ScanSendDelivery.propTypes = {
  onChange: React.PropTypes.func,
  sendData: React.PropTypes.array
};

ScanSendDelivery.defaultProps = {
  onChange: () => {},
  sendData: [],
  symbol: 'delivery-receive'
};


function mapStateToProps(state) {
  return {
    options: state.login.options,
  };
}

export default ScanSendDelivery;
